<template>
  <div>
    <div v-if="initLoading">
      正在初始化配置数据...
    </div>
    <div v-else>
      <div v-if="!hasInit">
        <div v-if="!tableCode||tableCode.length===0">没有tableCode参数</div>
        <div v-else>初始化配置数据失败</div>
      </div>
      <div v-else>
        <Add ref="add" :table="table" @ok="search"></Add>
        <Update ref="update" :table="table" @ok="search"></Update>
        <Batch ref="batch" :table="table" @ok="search"></Batch>
        <ZgSort
          ref="sort"
          :showBtn="false"
          @ok="handleSort"></ZgSort>
        <ZgAttach
          ref="attach"
          :showBtn="false"
          :attTypeArr="JSON.parse(table.attType)"
          :tableName="table.code"></ZgAttach>
        <ZgDataImport
          ref="import"
          :showBtn="false"
          fileName="test.xlsx"
          url="/dict/import"
          @ok="search">
        </ZgDataImport>
        <a-row :gutter="10">
          <a-col :span="leftWidth">
            <a-card>
              xxx
            </a-card>
          </a-col>
          <a-col :span="24-leftWidth">
            <ZgNewPage
              ref="page"
              :title="table.name"
              addBtnName="添加数据"
              :scrollX="2000"
              :conditions="conditions"
              :headers="headers"
              :pageOpt="pageOpt"
              :batchBtns="batchBtns"
              :dataBtns="dataBtns"
              :filter="filter"
              @search="onSearch"
              @filter="onFilter"
              @add="toAdd"
              @batch="toBatch"
              @admin="toAdmin"
            >
              <template slot="columns">
                <a-table-column
                  :width="column.width"
                  v-for="(column,i) in columns"
                  :key="`column${i}`"
                  :dataIndex="column.code"
                  :title="column.name">
                  <template slot-scope="text,record">
                    <div v-if="['单选框','开关'].includes(column.type)">
                      {{ record[column.code]===1?'是':'否' }}
                    </div>
                    <div v-else-if="['富文本'].includes(column.type)">
                      <div v-html="record[column.code]"></div>
                    </div>
                    <div class="w30 h30" v-else-if="['图片'].includes(column.type)">
                      <el-image
                        v-if="record&&record[column.code]"
                        :src="record[column.code]">
                      </el-image>
                    </div>
                    <div v-else>
                      {{ record[column.code] }}
                    </div>
                  </template>
                </a-table-column>
              </template>
              <template slot="thMode" slot-scope="scope">
                <a-row>
                  <a-col :span="4" v-for="t in scope.list" :key="`thMode_${t.id}`">
                    <a-card>
                      <div class="wfull h100 scroll">
                        {{ t }}
                      </div>
                    </a-card>
                  </a-col>
                </a-row>
              </template>
            </ZgNewPage>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>
<script>
import Add from './Add'
import Update from './Update'
import Batch from './Batch'
import Condition from './Condition'
import HeaderConfig from './HeaderConfig'
export default {
  components: {
    Add, Update, Batch, Condition, HeaderConfig
  },
  data () {
    return {
      showLeft: false,
      hasInit: false,
      initLoading: false,
      table: null,
      tableCode: 'form_test',
      columns: [],
      allColumns: [], // 缓存全部字段
      extra: {
        表单编码: '',
        属性列表: '',
        枚举编码: '',
        字典类型: '',
        行数: '3',
        高度: '400'
      },
      filter: { id: '0', name: '所有数据', count: 0, hasUse: true },
      pageOpt: {
        showSearchBtn: true,
        showRefreshBtn: true,
        showConditionBtn: true,
        showHeaderConfig: true,
        showAttachBtn: true,
        showLayoutMode: true
      },
      conditions: [],
      headers: [
        { code: 'name', label: '姓名', width: 120, isShow: true, sort: 0 },
        { code: 'sex', label: '性别', width: 120, isShow: true, sort: 0 },
        { code: 'age', label: '年龄', width: 120, isShow: true, sort: 0 }
      ],
      batchBtns: [
        { key: 1, label: '批量删除' },
        { key: 2, label: '批量修改' },
        { key: 3, label: '数据排序' },
        { key: 4, label: 'Excel导入' },
        { key: 5, label: 'Excel导出' }
      ],
      dataBtns: [
        { key: 1, name: '删除', icon: 'fa-trash', isShow: () => { return true } },
        { key: 2, name: '修改', icon: 'fa-pencil', isShow: () => { return true } },
        { key: 3, name: '附件', icon: 'fa-file', isShow: () => { return true } }
      ]
    }
  },
  computed: {
    leftWidth () {
      return this.showLeft ? 5 : 0
    },
    header () {
      return []
    }
  },
  mounted () {
    this.init()
  },
  watch: {
    $route (to, from) {
      this.init()
    }
  },
  methods: {
    search () {
      this.$refs.page.search()
    },
    fetchCondition (formId) {
      this.conditions = [
        { code: 'select', compType: '下拉选择', label: '性别', defaultVal: '', extra: { 下拉选项: [{ value: '1', label: '男111s' }, { value: '2', label: '女' }] } },
        { code: 'birth', compType: '日期区间', label: '生日', defaultVal: ['', ''] },
        { code: 'age', compType: '整数区间', label: '年龄', defaultVal: [0, 100] },
        { code: 'birth1', compType: '日期', label: '生日1', defaultVal: '2025-05-23' },
        { code: 'age1', compType: '整数', label: '年龄1', defaultVal: 0 },
        { code: 'name', compType: '单行文本', label: '姓名', defaultVal: '' },
        { code: 'political', compType: '字典', label: '政治面貌', defaultVal: '', extra: { 字典类型: 'political' } },
        { code: 'is_use', compType: '布尔', label: '启用1', defaultVal: 'false' },
        { code: 'other1', compType: '单行文本', label: 'other1', defaultVal: '' },
        { code: 'other2', compType: '单行文本', label: 'other2', defaultVal: '' },
        { code: 'other3', compType: '单行文本', label: 'other3', defaultVal: '' },
        { code: 'other4', compType: '单行文本', label: 'other4', defaultVal: '' },
        { code: 'other5', compType: '单行文本', label: 'other5', defaultVal: '' },
        { code: 'other6', compType: '单行文本', label: 'other6', defaultVal: '' },
        { code: 'other7', compType: '单行文本', label: 'other7', defaultVal: '' }
      ]
    },
    init () {
      this.hasInit = false
      // this.tableCode = this.$route.query.tableCode
      if (!this.tableCode || this.tableCode.length === 0) {
        return
      }
      this.initLoading = true
      const timer = setTimeout(() => {
        this.initLoading = false
      }, 10000)
      this.$http.get('/zg-autoform/form/oneByCode', { code: this.tableCode }, data => {
        this.pageOpt.showConditionBtn = data.hasFilter
        data.addColumns.forEach(c => {
          c.code = c.code.toLowerCase()
          try {
            c.extra = Object.assign({}, this.extra, JSON.parse(c.extra))
          } catch (e) {
            c.extra = JSON.parse(JSON.stringify(this.extra))
          }
        })
        data.updateColumns.forEach(c => {
          c.code = c.code.toLowerCase()
          try {
            c.extra = Object.assign({}, this.extra, JSON.parse(c.extra))
          } catch (e) {
            c.extra = JSON.parse(JSON.stringify(this.extra))
          }
        })
        data.batchColumns.forEach(c => {
          c.code = c.code.toLowerCase()
          try {
            c.extra = Object.assign({}, this.extra, JSON.parse(c.extra))
          } catch (e) {
            c.extra = JSON.parse(JSON.stringify(this.extra))
          }
        })
        data.allColumns.forEach(c => {
          c.code = c.code.toLowerCase()
        })
        this.table = data
        this.fetchCondition()
        this.findFilter()
        this.allColumns = data.allColumns
        this.mergeHeader(data.headers)
        clearTimeout(timer)
        this.initLoading = false
        this.hasInit = true
      }, (res) => {
        this.errorMsg = res.message
        this.initLoading = false
      })
    },
    findFilter () {
      /*
      this.$http.get('/zg-autoform/filter/list', { formId: this.table.id }, data => {
        const arr = [].concat(data[0]).concat(data[1])
        this.$refs.page.addFilter(arr.map(t => {
          return {
            id: t.id,
            name: t.name,
            condition: t.condition,
            count: 5
          }
        }))
      }) */
    },
    onSearch (param) {
      this.$http.post('/zg-autoform/table/data/page/' + this.table.code, param, data => {
        this.$refs.page.endSearch(
          {
            total: data[0],
            list: data[1].map(t => {
              const result = {
                key: t.ID
              }
              for (const key in t) {
                result[key.toLowerCase()] = t[key]
              }
              return result
            })
          }
        )
      })
    },
    onFilter (f, param) {
      // 切换数据视图
      this.$refs.condition.setCondition(f.condition)
      this.onSearchWithCondition(param)
    },
    onSearchWithCondition (param) {
      const condition = this.$refs.condition.getCondition()
      this.$http.post('/zg-autoform/table/data/page/' + this.table.code,
        Object.assign({}, param, JSON.parse(condition)),
        data => {
          this.$refs.page.endSearch(
            {
              total: data[0],
              list: data[1].map(t => {
                const result = {
                  key: t.ID
                }
                for (const key in t) {
                  result[key.toLowerCase()] = t[key]
                }
                return result
              })
            }
          )
        })
    },
    toAdd () {
      this.$refs.add.open()
    },
    toAdmin (param) {
      if (param.key === 1) {
        this.confirm(
        () => {
          this.$http.post('/zg-autoform/table/data/del/' + this.table.code, [param.obj.id], () => {
            this.$refs.page.search()
          })
        },
        '确定要删除这条数据么')
      } else if (param.key === 2) {
        this.$refs.update.open(param.obj)
      } else if (param.key === 3) {
        this.$refs.attach.open(param.obj)
      }
    },
    toBatch (opt) {
      if (opt.key === 1) {
        this.$refs.page.checkIds(ids => {
          this.$http.post('/zg-autoform/table/data/del/' + this.table.code, ids, () => {
            this.$refs.page.search()
          })
        }, '确定要批量删除这些数据')
      } else if (opt.key === 2) {
        this.$refs.page.checkIds(ids => {
          this.$refs.batch.open(ids)
        }, '确定要批量修改这些数据')
      } else if (opt.key === 3) {
        const list = this.$refs.page.getList()
        this.$refs.sort.open(list)
      } else if (opt.key === 4) {
        this.$refs.import.open()
      } else if (opt.key === 5) {
        this.$http.download('/zg-system/dict/export', {}, '字典数据.xlsx')
      }
    },
    handleSort (result) {
      alert(JSON.stringify(result.map(t => {
        return {
          id: t.id,
          sort: t.index
        }
      })))
    },
    mergeHeader (headers) {
      if (!headers) {
        return this.allColumns
      }
      let result = this.allColumns.map(t => {
        const arr = headers.filter(x => {
          return x.columnCode === t.code
        })
        t.width = arr.length > 0 ? arr[0].width : 120
        t.sort = arr.length > 0 ? arr[0].sort : 0
        t.isShow = arr.length > 0 ? arr[0].isShow : true
        return t
      })
      result = result.filter(t => {
        return t.isShow
      })
      result.sort((a, b) => {
        return a.sort - b.sort
      })
      this.columns = result
    }
  }
}
</script>

<style lang="scss" scoped>
.block{
  margin-bottom:10px;
  border:solid 1px #f2f2f2;
  border-radius:3px;;
  font-size:12px;
  &.active{
    background:#f2f2f2;
  }
  &:hover{
    cursor:pointer;
    background:#f2f2f2;
  }
}
</style>
